import { Component, AfterViewChecked, EventEmitter } from '@angular/core'
import * as moment from 'moment'
import { Store } from '@ngrx/store'
import * as fromRoot from '../../core/reducers'
import * as fromChecklist from '../../core/actions/checklist'
import { ITask } from '../../core/models'
import { IUpdateTaskDto } from '../../core/dtos'

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.less', '../../common/todo-list.less']
})

export class SearchComponent implements AfterViewChecked {
  resFromTitle: ITask[] = []
  resFromNotes: ITask[] = []
  isPure = true
  focusEvent = new EventEmitter<boolean>()
  constructor (private _store: Store<fromRoot.IState>) { }

  ngAfterViewChecked () {
    this.focusEvent.emit(true)
  }

  search (key): void {
    if (key) {
      this.isPure = false
      this._store.select(fromRoot.selectChecklists).subscribe((checklists) => {
        this.resFromNotes.length = 0
        this.resFromTitle.length = 0
        checklists.forEach((checklist) => {
          this.resFromNotes.push(...checklist.tasks.filter((v) => v.notes && v.notes.includes(key)).map((w) => {
            w.listId = checklist.id
            return w
          }))
          this.resFromTitle.push(...checklist.tasks.filter((v) => v.todo && v.todo.includes(key)).map((w) => {
            w.listId = checklist.id
            return w
          }))
        })
      })
      console.log(this.resFromNotes, this.resFromTitle)
    } else {
      this.isPure = true
      this.resFromNotes.length = 0
      this.resFromTitle.length = 0
    }
  }

  toggleDone (task: ITask, e: MouseEvent) {
    e.stopPropagation()
    const { index, isDone, listId } = task
    const dto: IUpdateTaskDto = {
      listId,
      index,
      ['isDone']: !isDone
    }
    this._store.dispatch(new fromChecklist.ToggleDoneTaskActin(dto))
  }

  renderDeadlineStyle (value: string, isDone: boolean) {
    if (isDone) { return }
    const deadline = moment(value.substring(0, 10))
    const now = moment(moment().format('YYYY-MM-DD'))
    return deadline.diff(now) >= 0
      ? '#465efc'
      : '#fc4646'
  }
}
